package com.zking.shiro.controller;

import com.zking.shiro.model.User;
import com.zking.shiro.service.IUserService;
import com.zking.shiro.shiroutils.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.misc.Cache;

@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    private IUserService iUserService;


    @RequestMapping("/dologin")
    public String dologin(User user){
        System.out.println("我是登录的方法");
        //实例化一个基于账号密码的令牌，将用户的账号，密码传到令牌的构造方法中
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        //通过SecurityUtils这个Shiro内置的工具类来获取实体对象subject
        Subject subject = SecurityUtils.getSubject();
        String str = null;


        try {
            //主体调用login方法，将令牌Token当做参数传到login方法中以便subject进行登录判断
            subject.login(token);
        } catch (UnknownAccountException e) {
            str = "账号不存在";
        } catch (LockedAccountException e) {
            str = "账号状态异常，请于管理员联系";
        } catch (IncorrectCredentialsException e) {
            str = "密码错误";
        }



        System.out.println(user);

        System.out.println(str);

        if (str == null) {
            return "index";
        }

        return null;
    }

    @RequestMapping("/updatepassword")
    public String updatepassword(User user) {
        System.out.println("我是修改密码的方法");
        System.out.println(user);

        User user1 = iUserService.loadByUsername(user);


        System.out.println(user1);

        String password1 = PasswordHelper.createCredentials(user1.getPassword(),user1.getSalt());

        System.out.println("正式加密"+password1);

//        String password2 = PasswordHelper.createCredentialsPassword(user1.getPassword());

        user.setPassword(password1);
        user.setUsername("zs");
        user.setUserId(1L);
        iUserService.updatePassword(user);

//        System.out.println("密码888888加密后"+password2);


        return null;
    }


}
